<?php
		// REDIS配置文件
		function RedisFile(){
			// return array('HOST' => '127.0.0.1','AUTH' => NULL);
			if (C('DB_HOST') == 'rm-2zeg3h7u61o6hmy7u.mysql.rds.aliyuncs.com') {
				// 阿里云REDIS服务器地址
				return array('HOST' => 'r-2ze0d26d8295a974.redis.rds.aliyuncs.com','AUTH' => 'Heard123');
			}else{
				// 测试REDIS服务器地址
				return array('HOST' => '127.0.0.1','AUTH' => '1024');
			}
		}

		// Redis写入操作函数
		function RedisSet($key,$value,$expire = NULL)
		{
				$Redis = new \Redis();
				$array = RedisFile();
				$Redis->connect($array['HOST'],6379);
				$Redis->auth($array['AUTH']);
				if(is_int($expire) && $expire) {
						return $Redis->set($key,$value,$expire);
				}else{
					 return $Redis->set($key,$value);
				}
		}

		// Redis读取操作函数
		function RedisGet($key)
		{
				$Redis = new \Redis();
				$array = RedisFile();
				$Redis->connect($array['HOST'],6379);
				$Redis->auth($array['AUTH']);
				return $Redis->get($key);
		}
	// Redis生成对象
	function RedisNew()
	{
		$Redis = new \Redis();
		$array = RedisFile();
		$Redis->connect($array['HOST'],6379);
		$Redis->auth($array['AUTH']);
		return $Redis;
	}
		// Redis删除key
		function RedisDelete($key)
		{
				$Redis = new \Redis();
				$array = RedisFile();
				$Redis->connect($array['HOST'],6379);
				$Redis->auth($array['AUTH']);
				$Redis->delete($key);
		}

		// 获取Redis用户信息
		function GetRedisData()
		{
				$Redis = new \Redis();
				$array = RedisFile();
				$Redis->connect($array['HOST'],6379);
				$Redis->auth($array['AUTH']);
				return json_decode($Redis->get(urlsafe_b64decode(cookie('SESSIONRID'))),TRUE);
		}
/**
 * 对称加密算法加密
 * @param String $string 需要加密的字串
 * @param String $skey 加密EKY
 * @return String
 */
function urlsafe_b64encode($string = '', $skey = 'heard') {
	// return $string;
	$strArr = str_split(base64_encode($string));
	$strCount = count($strArr);
	foreach (str_split($skey) as $key => $value)
		$key < $strCount && $strArr[$key].=$value;
	return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}

/**
 * 对称加密算法解密
 * @param String $string 需要解密的字串
 * @param String $skey 解密KEY
 * @return String
 */
function urlsafe_b64decode($string = '', $skey = 'heard') {
	// return $string;
	$strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
	$strCount = count($strArr);
	foreach (str_split($skey) as $key => $value)
		$key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
	return base64_decode(join('', $strArr));
}
function urlsafe_b64decode_uuid($string = '', $skey = 'uuid') {
	return $string;
	$strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
	$strCount = count($strArr);
	foreach (str_split($skey) as $key => $value)
		$key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
	return base64_decode(join('', $strArr));
}
function urlsafe_b64encode_uuid($string = '', $skey = 'uuid') {
	return $string;
	$strArr = str_split(base64_encode($string));
	$strCount = count($strArr);
	foreach (str_split($skey) as $key => $value)
		$key < $strCount && $strArr[$key].=$value;
	return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}
function p($var){
	echo "<pre>";
	print_r($var);
}
function getpage($count, $pagesize = 10) {
	$p = new Think\Page($count, $pagesize);
	$p->setConfig('header', '<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
	$p->setConfig('prev', '上一页');
	$p->setConfig('next', '下一页');
	$p->setConfig('last', '末页');
	$p->setConfig('first', '首页');
	$p->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
	$p->lastSuffix = false;//最后一页不显示为总页数
	return $p;
}
function get_orderid(){
	$rand = rand(1,999);
	list($t1,$t2)=explode(' ',microtime());
	return (float)sprintf('%.of',(floatval($t1)+floatval($t2))*2).$rand;
}
function do_curl($url,$data='',$agent=''){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);    //是否返回header头
	curl_setopt($ch, CURLOPT_TIMEOUT,10);    //超时时间
	if($data){
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
	}
	if($agent){
		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
	}
	$content = curl_exec($ch);
	curl_close($ch);
	return $content;
}
function curl_multi($json_data){
	$start = microtime(true);
	$ch_list = array();
	$downloader = curl_multi_init();
	foreach ($json_data as $key => $value) {
		$ch_list[$key] = curl_init($value['AccessTokenurl']);
		unset($value['AccessTokenurl']);
		// $json_data = json_encode($value);//转化成json数组让微信可以接收
		// p($json_data);
		$header = array();
		$header[] = 'Content-Type: application/x-www-form-urlencoded';
		curl_setopt($ch_list[$key], CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch_list[$key], CURLOPT_HEADER, 0);
		curl_setopt($ch_list[$key], CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
		curl_setopt($ch_list[$key], CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch_list[$key], CURLOPT_POST, 1);
		// curl_setopt($ch_list[$key], CURLOPT_NOSIGNAL, 1);
		// curl_setopt($ch_list[$key], CURLOPT_TIMEOUT_MS, 200);
		curl_setopt($ch_list[$key],CURLOPT_POSTFIELDS,json_encode($value));
		curl_multi_add_handle($downloader, $ch_list[$key]);
	}
	/*for ($i = 1;$i <= 5;++$i) {
			$ch_list[$i] = curl_init("http://test.binbin.com/curl/test.php?time={$i}");
			curl_setopt($ch_list[$i], CURLOPT_RETURNTRANSFER, true);
			curl_multi_add_handle($multi_ch, $ch_list[$i]);
	}*/
	// 轮询
do {
		while (($execrun = curl_multi_exec($downloader, $running)) == CURLM_CALL_MULTI_PERFORM) ;
		if ($execrun != CURLM_OK) {
				break;
		}

		// 一旦有一个请求完成，找出来，处理,因为curl底层是select，所以最大受限于1024
		while ($done = curl_multi_info_read($downloader))
		{
				// 从请求中获取信息、内容、错误
				$info = curl_getinfo($done['handle']);
				$output = curl_multi_getcontent($done['handle']);
				$error = curl_error($done['handle']);
				$res[] = $output;
				// 将请求结果保存,我这里是打印出来
//        print "一个请求下载完成!\n";

				// 把请求已经完成了得 curl handle 删除
				curl_multi_remove_handle($downloader, $done['handle']);
		}

		// 当没有数据的时候进行堵塞，把 CPU 使用权交出来，避免上面 do 死循环空跑数据导致 CPU 100%
		if ($running) {
				$rel = curl_multi_select($downloader, 1);
				if($rel == -1){
						usleep(1000);
				}
		}

		if( $running == false){
				break;
		}
} while (true);
	curl_multi_close($multi_ch);
	$end = microtime(true);
	echo "@|".date("H:i:s",time())."=".round($end-$start,3)."|@";
	return $res;
}
/**
 * author:10xjzheng
 * Excel导入
 * @param url 要生成的二维码的链接
 * @param flag 是否生成图片保存起来，1是，0否（只是动态生成）
 */
function createQRcode($url,$flag=0,$order_sn){
	vendor("phpqrcode.phpqrcode");
	// 纠错级别：L、M、Q、H
	$level = 'L';
	// 点的大小：1到10,用于手机端4就可以了
	$size = 4;
	// 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
	if($flag){
		$path = "Uploads/QRcode/";
		if(!file_exists($path)){
			mkdir($path, 0700);
		}
		// 生成的文件名
		$fileName = $path.$order_sn.'.png';
		QRcode::png($url, $fileName, $level, $size);
		return $fileName;
	}else{
		QRcode::png($url, false, $level, $size);
		exit;
	}
}


function moneyzero($money){
	if(floor($money)==$money){
		$money = intval($money);
	}
	return $money;
}

/**
 * 云片发送短信
 * @param mobile 手机号
 * @param type 1 资质 2 特殊能力
 */
function yunpian_send($mobile,$type,$data)
{
	switch ($type) {
		case '1':$text = "【听说Heard】亲爱的主播，你已通过审核，主播编号为".$data."，请登录网站，开始接单吧。邀请主播好友成功加入可增加信誉分2分！";
		break;
		case '2':$text = "【听说Heard】亲爱的主播，很遗憾通知你：你提交的资料未通过审核。未过审原因：".$data."。请登录网站完成修改并重新提交。";
		break;
		case '3':$text = "【听说Heard】亲爱的主播，你的".$data."能力已通过审核，请登录网站，开始接单吧。";
		break;
		case '4':$text = "【听说Heard】亲爱的主播，很遗憾通知你：你提交的".$data."能力未通过审核。未过审原因：".$data."。请登录网站完成修改并重新提交。";
		break;
		case '5':$text = "【听说Heard】亲爱的主播，你的主播认证已通过审核，请登录网站，开始接单吧。";
		break;
		case '6':$text = "【听说Heard】亲爱的主播，很遗憾通知你：你提交的认证资料未通过审核。未过审原因：".$data."。请登录网站完成修改并重新提交。";
		break;
		case '7':$text = "【听说Heard】亲爱的主播，你的订单没有通过验收，请在60分钟内登录网站完成重传，如有问题请尽快联系微信客服（heard365）。";
		break;
		case '8':$text = "【听说Heard】亲爱的主播，你收到来自《".$data."》的签约单，请在".$data."分钟内进入听说微信服务号或登录网站接单。";
		break;
		case '9':$text = "【听说Heard】亲爱的主播，你的签约单没有通过验收，请在".$data."分钟内登录网站完成重传，如有问题请尽快联系微信客服（heard365）。";
		break;
		case '10':$text = "【听说Heard】亲爱的主播，你有一笔极速派单超时未交，接单开关已被关闭，请尽快登录网站恢复接单。";
		break;
		case '11':$text = "【听说Heard】亲爱的主播，你邀请的".$data."主播顺利通过审核，你的信用分已增加2分。";
		break;
		case '12':$text = "【听说Heard】您已成功为".$data."账号充值".$data."元，此金额可在本账号下所有主体使用。";
		break;
		case '13':$text = "【听说Heard】此时段主播全忙，请稍后再试，退款已原路返还。";
		break;
		case '14':$text = "【听说Heard】您的订单因故未能交付，退款已原路返还，请尽快登录网站查看。";
		break;
		default:
			# code...
			break;
	}
	$apikey = 'f2e6926e1812968aa9ee73e15de0c2d1';
	return send_sms($apikey,$text,$mobile);
}

		/**
		* 智能匹配模版接口发短信
		* apikey 为云片分配的apikey
		* text 为短信内容
		* mobile 为接受短信的手机号
		*/
		function send_sms($apikey,$text,$mobile)
		{
				$url="http://yunpian.com/v1/sms/send.json";
				$encoded_text = urlencode("$text");
				$mobile = urlencode("$mobile");
				$post_string="apikey=$apikey&text=$encoded_text&mobile=$mobile";
				return sock_post($url, $post_string);
		}

		/**
		* url 为服务的url地址
		* query 为请求串
		*/
		function sock_post($url,$query)
		{
				$data = "";
				$info=parse_url($url);
				$fp=fsockopen($info["host"],80,$errno,$errstr,30);
				if(!$fp){
						return $data;
				}
				$head= "POST ".$info['path']." HTTP/1.0\r\n";
				$head.="Host: ".$info['host']."\r\n";
				$head.="Referer: http://".$info['host'].$info['path']."\r\n";
				$head.="Content-type: application/x-www-form-urlencoded\r\n";
				$head.="Content-Length: ".strlen(trim($query))."\r\n";
				$head.="\r\n";
				$head.=trim($query);
				$write=fputs($fp,$head);
				$header = "";
				while ($str = trim(fgets($fp,4096))) {
						$header.=$str;
				}
				while (!feof($fp)) {
						$data .= fgets($fp,4096);
				}
				return $data;
		}
function saveUrl(){
    session('returnUrl',$_SERVER['HTTP_REFERER']);
}

    /**
     * 腾讯科技curl请求
     */
    function http_post_json($url, $jsonStr)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $response;
    }

/**
* 输出execl
*/
function output_excel($filename='列表',$key=array(),$data=array())
{
	import("Org.Util.PHPExcel");
	$arr         = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W');
	$objPHPExcel = new \PHPExcel();
	$i           = 1;
	$i_key		= 0;
	$objPHPExcel->getDefaultStyle()->getFont()->setSize(12);
	foreach ($key as $k =>&$val)
	{
		$objPHPExcel->getActiveSheet()->setCellValue($arr[$k].'1',$val);
	}
	$i = $i+1;
	foreach ($data as $key=>&$r)
	{
		foreach($r as &$val)
		{
			$objPHPExcel->getActiveSheet()->setCellValue($arr[$i_key].$i, $val);
			$i_key++;
		}
		$i_key=0;
		$i++;
	}

	$objPHPExcel->getActiveSheet()->setTitle($filename);
	header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8');
	header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
	header('Cache-Control: max-age=0');
	import("Org.Util.PHPExcel.IOFactory");
	// $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	$objWriter->save('php://output');
}
/**
 * 为url添加域名
 */
function url_add_domainname($url){
	if(empty($url)){return $url;}
	if (strpos($url, "audio.heardtech.com") === false) {
		$url = "http://audio.heardtech.com/".$url;
	}
	return $url;
}

function import_excel($file)
{
	// 判断文件是什么格式
	$type = pathinfo($file);
	$type = strtolower($type["extension"]);
	$type = $type === 'csv' ? $type : 'Excel5';
	ini_set('max_execution_time', '0');
	Vendor('PHPExcel.PHPExcel');
	// 判断使用哪种格式
	$objReader = PHPExcel_IOFactory::createReader($type);
	$objPHPExcel = $objReader->load($file);
	$sheet = $objPHPExcel->getSheet(0);
	// 取得总行数
	$highestRow = $sheet->getHighestRow();
	// 取得总列数
	$highestColumn = $sheet->getHighestColumn();
	//循环读取excel文件,读取一条,插入一条
	$data = array();
	//从第一行开始读取数据
	for ($j = 2; $j <= $highestRow; $j++) {
		//从A列读取数据
		for ($k = 'A'; $k <= $highestColumn; $k++) {
			// 读取单元格
			$data[$j][] = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
		}
	}
	return $data;
}